#include <cppr.hpp>
using namespace std;
class MyException
{
protected:
    char msg[128];

public:
    MyException(const char *pmsg)
    {
        if (strlen(pmsg) < 128)  //判断字符串长度是否小于128
        {
            strcpy(msg, pmsg); 
        }
        else
        {
            strcpy(msg, "请简化信息"); //如果字符串长度大于128，则提示简化信息
        }
    }
    virtual const char *what() 
    {
        return msg;
    }
};

class connectException : public MyException
{
    private:
        char ip[128];
        char port[128];
    public:
        connectException(const char *pmsg,const char *pip,const char *pport):MyException(pmsg)
        {
            strcpy(ip,pip);
            strcpy(port,pport);
        }
        virtual const char *what()
        {
            char *tmp=new char[256];
            sprintf(tmp,"%s  ip:%s  port:%s",msg,ip,port);
            return tmp;
        }
};

void connectservice(const char *ip,const char *port)
{
    int sd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family=AF_INET;
    addr.sin_port=htons(atoi(port));
    addr.sin_addr.s_addr=inet_addr(ip);
    if(connect(sd,(struct sockaddr*)&addr,sizeof(addr))==-1)
    {
        throw new connectException("连接失败",ip,port);
    }
    close(sd); 
    //关闭套接字 
    //close(sd); 语句不会被执行，因为它位于抛出异常的语句之后。当异常被抛出时，程序会立即停止执行当前函数中的后续语句，并开始查找异常处理程序。
}

int main()
{
    try
    {
        connectservice("127.0.0.1","8888");
    }
    catch(MyException *e)
    {
        cout<<e->what()<<endl;
    }
    return 0;
}